from fastapi import FastAPI
from fastapi_amis_admin.admin.settings import Settings
from fastapi_user_auth.admin.site import AuthAdminSite
from starlette.requests import Request
from sqlmodel import SQLModel
from fastapi_amis_admin.admin import admin


# Create FastAPI application
from vehicel.models import Vehicle

app = FastAPI()

# Create AdminSite instance
site = AuthAdminSite(settings=Settings(database_url='mysql+pymysql://root:1Kff6Jm*uGLZY_OJKlK_fzS3rJY_xZ@192.168.2.161:3306/demo?charset=utf8mb4'))
auth = site.auth

@site.register_admin
class VehicleAdmin(admin.ModelAdmin):
    page_schema = 'Vehicle'
    # set model
    model = Vehicle

# Mount the backend management system
site.mount_app(app)





# # Create initial database table
@app.on_event("startup")
async def startup():
    await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False)
#     # Create a default administrator, username: admin, password: admin, please change the password in time!!!
#     await auth.create_role_user("admin")
#     #Create the default super administrator, username: root, password: root, please change the password in time!!!    await auth.create_role_user("root")
#     # Run the startup method of the site, load the casbin strategy, etc.
#     await site.router.startup()
#     #Add a default casbin rule
#     if not auth.enforcer.enforce("u:admin", site.unique_id, "page", "page"):
#         await auth.enforcer.add_policy("u:admin", site.unique_id, "page", "page", "allow")


# Requirements: User must be logged in
@app.get("/auth/get_user")
@auth.requires()
def get_user(request: Request):
    return request.user


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app)
